import {
	createStore
} from 'vuex';
import api from '../api';

export default createStore({
	state: {
		user: null,
		token: localStorage.getItem('token') || '',
	},
	mutations: {
		setUser(state, user) {
			state.user = user;
		},
		setToken(state, token) {
			state.token = token;
			if (token) {
				localStorage.setItem('token', token);
			} else {
				localStorage.removeItem('token');
			}
		},
	},
	actions: {
		async login({
			commit
		}, credentials) {
			try {
				const response = await api.login(credentials);
				commit('setToken', response.data.token);
				// You might want to fetch user data here and commit setUser mutation
				// const userResponse = await api.getUserData();
				// commit('setUser', userResponse.data);
			} catch (error) {
				console.error('Login failed:', error);
				throw error;
			}
		},
		logout({
			commit
		}) {
			commit('setToken', '');
			commit('setUser', null);
		},
	},
	getters: {
		isAuthenticated: state => !!state.token,
		user: state => state.user,
	},
});